package com.agent.util;

import com.agent.domain.AgentInfo;
import com.agent.domain.AgentInfoMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
 * 数据库连接工具
 */
public class DBUtil {
    public static SqlSession getSession(){
        // 1. 加载配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 2. 创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 3. 获取SqlSession  true表示自动提交
        return  sqlSessionFactory.openSession(true);
    }


    public static void testDB() {
        AgentInfoMapper agentInfoMapper = DBUtil.getSession().getMapper(AgentInfoMapper.class);
        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setCostTime(0);
        agentInfo.setFunctionName("test"+System.currentTimeMillis());
        agentInfoMapper.insertAgentInfo(agentInfo);
    }

}
